package com.uuzuche.lib_zxing;

/**
 * @author yulu
 * @date 2016年11月29日 下午3:39:09
 * @email yulu@cecurs.com
 */

import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;



public class ImageUtil {

    /**
     * 读取图片属性：旋转的角度
     *
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return degree;
        }
        return degree;
    }

    /**
     * 旋转图片，使图片保持正确的方向。
     *
     * @param bitmap  原始图片
     * @param degrees 原始图片的角度
     * @return Bitmap 旋转后的图片
     */
    public static Bitmap rotateBitmap(Bitmap bitmap, int degrees) {
        if (degrees == 0 || null == bitmap) {
            return bitmap;
        }
        Matrix matrix = new Matrix();
        matrix.setRotate(degrees, bitmap.getWidth() / 2, bitmap.getHeight() / 2);
        Bitmap bmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                bitmap.getHeight(), matrix, true);
        if (null != bitmap) {
            bitmap.recycle();
        }
        return bmp;
    }


    public static String getIconPath(Context context, Intent data) {
        String path = "";
        Uri originalUri = data.getData(); // 获得图片的uri
        Log.i("MainActivity", "originalUri" + originalUri);
        String[] proj = {MediaStore.Images.Media.DATA};
        // android多媒体数据库的封装接口
        Cursor cursor = context.getContentResolver().query(originalUri, proj,
                null, null, null);
        // 这个是获得用户选择的图片的索引值
        int column_index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
        // 将光标移至开头 ，这个很重要，不小心很容易引起越界
        cursor.moveToNext();
        // 最后根据索引值获取图片路径
        path = cursor.getString(column_index);
        Log.i("MainActivity", "path" + path);

        return path;
    }

    /**
     *bitmap转换为二进制数组
     *
     */
    public static byte[] bitmapToByte(Bitmap bitmap){
        byte[] imageByte=null;
        if (bitmap!=null){
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.JPEG, 100, out);
            try {
                out.flush();
                out.close();
                imageByte = out.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        return imageByte;
    }

    /**
     * base64String 转为bitmap
     *
     * @param base64Data
     * @return
     */
    public static Bitmap base64ToBitmap(String base64Data) {
        byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    /**
     * 将Bitmap转换成Base64String
     *
     * @return
     */

    public static String bitmapToBase64(Bitmap bitmap) {
        String transResult = null;
        if (null != bitmap) {
            ByteArrayOutputStream outInitial = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.JPEG, 100, outInitial);
            try {
                outInitial.flush();
                outInitial.close();
                byte[] bitmapInitialBytes = outInitial.toByteArray();
                float length = (float)bitmapInitialBytes.length;
               float bitmapInitialSize= length/(1024*1024);
//                如果相册中的图片的字符流小于1M,则不压缩
                if (bitmapInitialSize<1.0){
                   transResult=  Base64.encodeToString(bitmapInitialBytes, Base64.DEFAULT);
                    return transResult;
                }
            } catch (IOException e) {
            }
            Matrix matrix = new Matrix();
            matrix.setScale(0.3f, 0.3f);
            Bitmap bitmapCompress = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            bitmapCompress.compress(CompressFormat.JPEG, 100, out);
            try {
                out.flush();
                out.close();
                byte[] imageBytes = out.toByteArray();
                float length = (float) imageBytes.length;
                 float bitmapCompreSize = length/(1024*1024);
                if (bitmapCompreSize>1.0){
                    Matrix matrix2 = new Matrix();
                    matrix2.setScale(0.5f, 0.5f);
                    Bitmap bitmapCompress2 = Bitmap.createBitmap(bitmapCompress, 0, 0, bitmapCompress.getWidth(), bitmapCompress.getHeight(), matrix2, true);
                    ByteArrayOutputStream out2 = new ByteArrayOutputStream();
                    bitmapCompress2.compress(CompressFormat.JPEG, 100, out2);
                    out2.flush();
                    out2.close();
                    byte[] bytes = out2.toByteArray();
                    float length2 = (float) bytes.length;
                    float bitmapCompreSize2 = length2/(1024*1024);
                    transResult = Base64.encodeToString(bytes, Base64.DEFAULT);
                    return transResult;
                }
                transResult = Base64.encodeToString(imageBytes, Base64.DEFAULT);
            } catch (IOException e) {
            }
        }
        return transResult;
    }

    /**
     * 将Bitmap转换成Base64String
     *
     * @return
     */

    public static String bitmapToBase64_Camera(Bitmap bitmap) {
        String transResult = null;
        if (null != bitmap) {
            ByteArrayOutputStream outInitial = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.JPEG, 100, outInitial);
            try {
                outInitial.flush();
                outInitial.close();
                byte[] bytes = outInitial.toByteArray();
                float length = (float)bytes.length;
                float bitmapCameraSize= length/(1024*1024);
            } catch (IOException e) {
            }
            Matrix matrix = new Matrix();
            matrix.setScale(1.0f, 1.0f);
            Bitmap bitmap2 = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            bitmap2.compress(CompressFormat.JPEG, 100, out);
            try {
                out.flush();
                out.close();
                byte[] imageBytes = out.toByteArray();
                float length = (float) imageBytes.length;
                float bitmap2CompreSize = length/(1024*1024);
                transResult = Base64.encodeToString(imageBytes, Base64.DEFAULT);
            } catch (IOException e) {
            }
        }
        return transResult;
    }

    /**
     * 获取选取的照片对象
     *
     * @param imgPath
     * @return
     */
    public static Bitmap getPhotoBitmap(String imgPath) {
        Bitmap bitmap = null;
        try {
            if (null != imgPath && imgPath.length() > 0) {
                bitmap = BitmapFactory.decodeFile(imgPath);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            bitmap = null;
        }
        return bitmap;
    }

    public static Bitmap getbitMap(String url) {
        Bitmap bitMap = null;
        File file = new File(url);
        if (file.exists()) {
            bitMap = BitmapFactory.decodeFile(url);
        }
        return bitMap;
    }

    public static void inforMedia(Context context, File file, String fileName) {
        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(file.getPath()))));
    }

    public static boolean savePicture(Context context, View rootView) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;
        Bitmap bitmap = Bitmap.createBitmap(screenWidth, screenHeight,
                Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        rootView.draw(canvas);

        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "gzt");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".png";
        File file = new File(appDir + fileName);
        FileOutputStream f = null;
        try {
            f = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
        boolean b = bitmap.compress(CompressFormat.PNG, 100, f);
        try {
            f.flush();
            f.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (b) {
            // 截图成功
            inforMedia(context, file, fileName);
            return true;
        }
        return false;
    }


    public static void saveImageToGallery(Context context, View v) {
        View view = v.getRootView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
        File folder = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                        + "/Whatever/");
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(),
                "Boohee");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir + fileName);

        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String path = Environment.getExternalStorageDirectory() + "/Boohee"
                + fileName;
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.parse("file://" + path)));
    }


    /**
     * 根据Uri获取图片绝对路径，解决Android4.4以上版本Uri转换
     *
     * @param context
     * @param imageUri
     */
    @TargetApi(19)
    public static String getImageAbsolutePath(Context context, Uri imageUri) {
        if (context == null || imageUri == null)
            return null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) {
            if (isExternalStorageDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(imageUri)) {
                String id = DocumentsContract.getDocumentId(imageUri);
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } // MediaStore (and general)
        else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(imageUri))
                return imageUri.getLastPathSegment();
            return getDataColumn(context, imageUri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            return imageUri.getPath();
        }
        return null;
    }

    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String column = MediaStore.Images.Media.DATA;
        String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }


    public static String getPhotoPath(Context context, Uri photoUri, Intent data) {
        String photoPath = "";
        ContentResolver cr = context.getContentResolver();
        if (photoUri != null) {
            Cursor cursor = cr.query(photoUri, null, null, null, null);
            if (cursor != null && cursor.getCount() > 0) {
                cursor.moveToFirst();
                int pathIndex = cursor
                        .getColumnIndex(MediaStore.Images.Media.DATA);
                photoPath = cursor.getString(pathIndex);
                cursor.close();
            }
        } else {
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null && !TextUtils.isEmpty(uri.getPath())) {
                    photoPath = uri.getPath();
                    if (!(new File(photoPath).exists())) {
                        String[] proj = {MediaStore.Images.Media.DATA};
                        Cursor actualimagecursor = cr.query(uri, proj, null,
                                null, null);
                        int actualImg = actualimagecursor
                                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        actualimagecursor.moveToFirst();
                        if (actualimagecursor != null)
                            photoPath = actualimagecursor.getString(actualImg);
                    }
                }
            }
        }
        return photoPath;
    }



}
